﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using Zeus.Thunder.Core;
using System.IO;

namespace SharpTrainer.Concurrency
{
    class BetterAsynDownloadTest : ITestCase
    {
        public void Run()
        {
            string url = @"http://www.apress.com";

            Task<string> downloadTask = BetterDownloadWebPageAsync(url);
            int i = 1;
            while (!downloadTask.IsCompleted)
            {
                if (i++ % 50 == 0)
                    Console.WriteLine();
                else
                    Console.Write(".");

                Thread.Sleep(250);
            }

            Console.WriteLine(downloadTask.Result);
        }

        private Task<string> BetterDownloadWebPageAsync(string url)
        {
            WebRequest request = WebRequest.Create(url);
            IAsyncResult ar = request.BeginGetResponse(null, null);
            Task<string> downloadTask =
                Task.Factory
                .FromAsync<string>(ar, iar =>
                {
                    using (WebResponse response = request.EndGetResponse(iar))
                    {
                        using (var reader = new StreamReader(response.GetResponseStream()))
                        {
                            return reader.ReadToEnd();
                        }
                    }
                });

            return downloadTask;
        }
    }
}
